//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.lujieni.springbootmybatis.handler;

import cn.hutool.core.lang.Assert;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.extra.spring.SpringUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class EncryptTypeHandler extends BaseTypeHandler<String> {
    private static final Logger log = LoggerFactory.getLogger(EncryptTypeHandler.class);
    private static final String ENCRYPTOR_PROPERTY_NAME = "mybatis-plus.encryptor.password";
    private static AES aes;

    static {
        String password = SpringUtil.getProperty(ENCRYPTOR_PROPERTY_NAME);
        Assert.notEmpty(password, "配置项({}) 不能为空", new Object[]{ENCRYPTOR_PROPERTY_NAME});
        aes = SecureUtil.aes(password.getBytes());
    }

    public EncryptTypeHandler() {
    }

    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, encrypt(parameter));
    }

    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return decrypt(value);
    }

    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return decrypt(value);
    }

    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return decrypt(value);
    }

    public static String decrypt(String value) {
        try {
            return value == null ? null : getEncryptor().decryptStr(value);
        } catch (Exception var2) {
            Exception e = var2;
            log.error("ERROR method EncryptTypeHandler.decrypt : {} ", e.getLocalizedMessage());
            return value;
        }
    }

    public static String encrypt(String rawValue) {
        try {
            return rawValue == null ? null : getEncryptor().encryptBase64(rawValue);
        } catch (Exception var2) {
            Exception e = var2;
            log.error("ERROR method EncryptTypeHandler.encrypt : {} ", e.getLocalizedMessage());
            return rawValue;
        }
    }

    /**
     * 如果无法成为Bean，确保SpringUtil已初始化
     * @return
     */
    private static AES getEncryptor() {
        return aes;
    }
}
